//
//
//
//
//
//
//
// TCPServer.h

#ifndef _TCPSERVER_H_
#define _TCPSERVER_H_

#include "TCPSocket.h"
#include "NetAddr.h"
#include <sys/select.h>
#include <sys/time.h>
#include <map>
class TimeVal;
class SocketHandleBase;
class TCPServer
{
	public:
		enum SOCKET_STATUS
		{
			SOCK_INVALIDE 	= 1,
			SOCK_INITIALED 	= 2,
			SOCK_LISTEN		= 3,
			SOCK_WAIT4CLOSE	= 4,
			SOCK_CLOSED		= 5,
		};
	public:
		TCPServer(const NetAddr& addr);
		~TCPServer();
		// handle network events, this should be called from 
		// external thread.
		// if timeout, it will return -2
		// throw exception if any unexpected data comes.
		int HandleEvents(const TimeVal& time);
		void RegisterHandler(SocketHandleBase* wor, Socket::EVENTS_OPT mask);

	private:
		TCPServer(const TCPServer&);
		TCPServer& operator=(const TCPServer&);

		U32 GetMaxFD() const;
		void RouteMsg(TCPSocket& sock, Socket::EVENTS_OPT event);
		void RemoveSocket(TCPSocket& sock);
	private:
		NetAddr _bindAddr;
		TCPSocket _serverSock;
		SOCKET_STATUS _sockStatus;
		
		int _maxFD;
		SocketHandleBase* _evnHandler;
		U32 _evnMask;

		std::map<S32, TCPSocket> _children;
		fd_set _rdSet;
		fd_set _wtSet;
		fd_set _expSet;
};

#endif // _TCPSERVER_H_

